// 开启babel，用来支持ES6语法
require('@babel/register')({
  presets: ['@babel/preset-env', '@babel/preset-typescript'],
  plugins: [],
  extensions: ['.ts', '.tsx'],
});
// 引入翻译API
const { youdao, baidu, google } = require('arvin-trans');

/**
 * 翻译 https://www.npmjs.com/package/arvin-trans
 * @param {*} from 待翻译语言类型
 * @param {*} to 目标语言类型
 * @param {*} q  待翻译内容
 * @param {*} impl  待翻译内容 youdao, baidu, google
 */
const translate = async ({ text = '', from = 'en', to = 'zh-CN', impl = 'baidu' }) => {
  let serviceImpl;
  if (impl === 'youdao') {
    serviceImpl = youdao;
  } else if (impl === 'google') {
    serviceImpl = google;
  } else {
    serviceImpl = baidu;
  }
  const result = await serviceImpl.translate({ text, from, to });
  return result.result.join('');
};

// ------------------------------------------------------------------------------------------------------------------------------------------
const lodash = require('lodash');
const fs = require('fs');
const path = require('path');

// 所有支持的语言
const languageArray = {
  // enUS: { dir: "en-US", youdao: "en", baidu: "en", google: "en" },
  // ptBR: { dir: "pt-BR", youdao: "pt", baidu: "pt", google: "pt" },
  zhCN: { dir: 'zh-CN', youdao: 'zh-CHS', baidu: 'zh', google: 'zh-CN' },
  zhTW: { dir: 'zh-TW', youdao: 'yue', baidu: 'yue', google: 'zh-TW' },
};
// 确定需要翻译的文件
const basePath = path.resolve('./src/locales');
const language = languageArray.zhCN.dir;
const fileName = 'component';
const locales = require(`${basePath}/${language}/${fileName}`).default;
// 翻译服务选择 google > youdao > baidu
const impl = 'google';

lodash.forEach(languageArray, async (languageItem: any) => {
  if (languageItem.dir === language) {
    return;
  }
  let to = languageItem[impl];
  if (!to) {
    to = languageItem.dir;
  }
  const targetText = {};
  for (const key in locales) {
    // noinspection JSUnfilteredForInLoop
    const value = locales[key];
    const text = await translate({ text: value, from: language, to, impl });
    console.log(`[${to}] | ${value} ---> ${text}`);
    // noinspection JSUnfilteredForInLoop
    targetText[key] = text;
  }
  // 翻译结果写入文件
  const filePath = `${basePath}/${languageItem.dir}/${fileName}-i18n.ts`;
  fs.writeFile(filePath, `export default ${JSON.stringify(targetText, null, 2)}`, (error: any) => {
    if (error) {
      console.log(`写入文件失败,原因是 ${error.message}`, error);
      return;
    }
    console.log('写入成功 --> ', filePath);
  });
});
